import plugin from "../../../lib/plugins/plugin.js";
import common from "../../../lib/common/common.js";
import fs from "fs";
import path from "path";

let pluginsPath = "./plugins";
let disabledPluginsPath = "./data/Disabled plugins";

export default class example extends plugin {
  constructor() {
    super({
      name: "[Xs插件]插件管理",
      dsc: "启用/禁用插件包",
      event: "message",
      priority: -114514,
      rule: [
        {
          reg: "^#启用插件.*$",
          fnc: "enablePlugin",
        },
        {
          reg: "^#禁用插件.*$",
          fnc: "disablePlugin",
        },
        {
          reg: "^#被禁用插件列表$",
          fnc: "listDisabledPlugins",
        },
        {
          reg: "^#插件包列表$",
          fnc: "listPlugins",
        },
      ],
    });
  }

  async enablePlugin(e) {
    if (!this.e.isMaster) {
      e.reply("你没有权限启用插件");
      return false;
    }

    let pluginName = e.msg.replace(/^#启用插件/g, "");
    let pluginPath = path.join(disabledPluginsPath, pluginName);

    if (!fs.existsSync(pluginPath)) {
      e.reply(`插件${pluginName}不存在`);
      return false;
    }

    let enabledPluginPath = path.join(pluginsPath, pluginName);

    fs.renameSync(pluginPath, enabledPluginPath);
    e.reply(`插件${pluginName}已启用，请手动重启`);
    return true;
  }

  async disablePlugin(e) {
    if (!this.e.isMaster) {
      e.reply("你没有权限禁用插件");
      return false;
    }

    let pluginName = e.msg.replace(/^#禁用插件/g, "");
    let pluginPath = path.join(pluginsPath, pluginName);

    if (!fs.existsSync(pluginPath)) {
      e.reply(`插件${pluginName}不存在`);
      return false;
    }

    let disabledPluginPath = path.join(disabledPluginsPath, pluginName);

    if (!fs.existsSync(disabledPluginsPath)) {
      fs.mkdirSync(disabledPluginsPath);
    }

    fs.renameSync(pluginPath, disabledPluginPath);
    e.reply(`插件${pluginName}已禁用，请手动重启`);
    return true;
  }

  async listDisabledPlugins(e) {
    let disabledPlugins = fs.readdirSync(disabledPluginsPath);

    if (disabledPlugins.length === 0) {
      e.reply("没有被禁用的插件");
      return false;
    }

    let msg = "被禁用插件：\n";
    for (let plugin of disabledPlugins) {
      msg += `${plugin}\n`;
    }

    e.reply(msg);
    return true;
  }

  async listPlugins(e) {
    let plugins = fs.readdirSync(pluginsPath);

    if (plugins.length === 0) {
      e.reply("没有插件");
      return false;
    }

    plugins.sort((a, b) => {
      return parseInt(a) - parseInt(b);
    });

    let msg = "已安装插件：\n";
    for (let plugin of plugins) {
      msg += `${plugin}\n`;
    }

    e.reply(msg);
    return true;
  }
}